#import "FLDRadioGroup.h"

@implementation FLDRadioGroup


@synthesize delegate;
@synthesize selectedIndex;
@synthesize selectedButton;

-(id)init
{
	if(self=[super init]){
		buttons = [[NSMutableArray alloc] initWithCapacity:1];
	}
	return self;
}


-(void)addButton:(UIButton*)button
{
	if([buttons containsObject:button])
		return;	
	[buttons addObject:button];
	[button addTarget:self action:@selector(_buttonDidSelect:) forControlEvents:UIControlEventTouchUpInside];
}


-(void)removeButton:(UIButton*)button
{
	if(button==selectedButton)
		selectedButton = nil;
	
	if([buttons containsObject:button]){
		[button removeTarget: self action: @selector(_buttonDidSelect:) forControlEvents: UIControlEventTouchUpInside];
	}
}


-(void)removeAllButtons
{
	selectedButton = nil;
	for(int i=0; i<[buttons count]; i++){
		[[buttons objectAtIndex:i] removeTarget: self action: @selector(_buttonDidSelect:) forControlEvents: UIControlEventTouchUpInside];

	}
	[buttons removeAllObjects];
}


-(NSInteger)selectedIndex
{
	return [buttons indexOfObject:selectedButton];
}


-(void)setSelectedIndex:(NSInteger)index
{
	if(index<0 || index >= [buttons count])
		return;
	
	UIButton *theButton = [buttons objectAtIndex:index];
	if(theButton==selectedButton)
		return;
	[self setSelectedButton: theButton];
}


-(UIButton*)selectedButton
{
	return selectedButton;
}


-(void)setSelectedButton:(UIButton*)button
{
	if(selectedButton==button)
		return;
	
	if(![buttons containsObject:button])
		return;
		
	if(selectedButton)
		selectedButton.selected = NO;
	button.selected = YES;
	selectedButton = button;
}


//private action handler for buttons
-(void)_buttonDidSelect:(id)button
{
	if( selectedButton != button ){
		[self setSelectedButton:button];	
		if(delegate){
			if([(NSObject*)delegate respondsToSelector: @selector(radioGroup:didSelecteButton:atIndex:)])
				[delegate radioGroup:self didSelecteButton:button atIndex:[self selectedIndex]];
		}
	}
}


-(void)dealloc
{
	[buttons release];
	[super dealloc];
}

@end
